package com.gx.smart.building.ui.warning

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.gx.smart.building.R
import com.gx.smart.building.databinding.ActivityFaultReportBinding
import com.gx.smart.building.ui.common.activity.BaseMVVMActivityUploadFileV4
import com.gx.smart.building.ui.repair.AssetsActivity
import com.gx.smart.building.ui.report.FaultRecordActivity
import com.gx.smart.building.ui.report.model.SubTypeLabel
import com.gx.smart.building.ui.warning.event.WarningMessageEvent
import com.gx.smart.building.ui.warning.viewmodel.WarningViewModel
import com.gx.smart.common.util.AppConfig
import com.gx.smart.lib.http.api.response.MessageAlarm
import com.gx.smart.lib.widget.dialog.CustomAlertDialog
import com.huishi.gx.ib.grpc.lib.ib.app.workorder.v1.dto.WorkOrderFileDto
import com.mylhyl.circledialog.CircleDialog
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class FaultReportActivity : BaseMVVMActivityUploadFileV4<WarningViewModel>() {
    private lateinit var viewBinding: ActivityFaultReportBinding
    private lateinit var detail: MessageAlarm
    private var dealType: Int = 0
    private var orderTypeId: String? = null
    private var orderTypeCode: String? = null
    private var orderTypeName: String? = null
    private var orderSubTypeId: String? = null
    private var orderSubTypeCode: String? = null
    private var orderSubTypeName: String? = null

    private var files: MutableList<WorkOrderFileDto.Builder> = mutableListOf()
    private var voiceFile: WorkOrderFileDto.Builder? = null
    private val items: MutableList<SubTypeLabel> = mutableListOf()
    private var uploadAudioStatus: Int = -1;//-1：没有上传音频 1：正常上传音频 2：上传音频成功 3：上传音频失败
    private var isVoiceRecord: Boolean = true
    private var isRunning: Boolean = false
    private var assetId: String? = null
    private var assetName: String? = null

    /**
     * 同步图片信息
     */
    private fun setImages() {
        //去除删除的图片
        picList1.filter { attachmentList1.map { item -> item.fileName }.contains(it.fileName) }
            .forEach { item ->
                files.add(
                    WorkOrderFileDto.newBuilder()
                        .setFileType(1)
                        .setFileName(item.fileName)
                        .setFileUrl(item.path)
                )
            }
    }

    override fun onBindViewModel(): Class<WarningViewModel> = WarningViewModel::class.java

    override fun onBindLayout(): Int = R.layout.activity_fault_report

    override fun getToolbarTitle(): String = "故障上报"

    override fun initContentView(root: ViewGroup?) {
        viewBinding = ActivityFaultReportBinding.inflate(layoutInflater, root, true)
        dealType = intent.getIntExtra("dealType", 0)
        viewBinding.select.setOnClickListener {
            startActivity(Intent(this, AssetsActivity::class.java))
        }
        viewBinding = ActivityFaultReportBinding.inflate(layoutInflater, root, true)
        viewBinding.list.setOnClickListener {
            startActivity(Intent(this, FaultRecordActivity::class.java))
        }
        viewBinding.save.setOnClickListener {
            submit()
        }
        viewBinding.subTypeName.setOnClickListener {
            CircleDialog.Builder()
                .setItems(items) { _: AdapterView<*>?, _: View?, position: Int, _: Long ->
                    orderSubTypeId = items[position].subTypeId
                    orderSubTypeCode = items[position].subTypeCode
                    orderSubTypeName = items[position].subTypeName
                    viewBinding.subTypeName.text = items[position].content
                    true
                }
                .setNegative("取消", null)
                .show(supportFragmentManager)
        }
        viewBinding.description.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable) {
                viewBinding.wordCount.text = s.length.toString() + "/200"
            }
        })
        viewBinding.voiceLayout.setOnClickListener {
            if (isVoiceRecord) {
                audioRecorder()
            } else {
                audioPlayUI()
            }

        }
        viewBinding.delete.setOnClickListener {
            deleteVoice()
        }
        initAudioPlayer()
        registerEventBus()
    }

    private fun audioPlayUI() {
        isRunning = !isRunning
        if (isRunning) {
            audioPlay()
            Glide.with(this).asGif().load(R.drawable.ic_voice_play).into(viewBinding.voicePlay)
        } else {
            audioPlayPause()
            Glide.with(this).load(R.mipmap.ic_voice_play).into(viewBinding.voicePlay)
        }
    }

    private fun deleteVoice() {
        viewBinding.voiceContent.visibility = View.VISIBLE
        viewBinding.voicePlay.visibility = View.GONE
        viewBinding.voiceDuration.visibility = View.GONE
        viewBinding.delete.visibility = View.GONE
        isVoiceRecord = true
        uploadAudioStatus = -1
        voiceFile = null
        audioPlayPause()
    }

    private var duration: Long = 0
    private fun audioRecorder() {
        if (AndPermission.hasPermissions(
                this, Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.RECORD_AUDIO
            )
        ) {
            voice()
        } else {
            voicePermission()
        }

    }

    private fun voicePermission() {
        //权限判断
        AndPermission.with(this)
            .runtime()
            .permission(
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.RECORD_AUDIO
            )
            .onGranted { permissions: List<String?>? ->
                voice()
            }
            .onDenied { permissions: List<String?>? ->
                ToastUtils.showLong("没有获取访问相册的权限")
                if (AndPermission.hasAlwaysDeniedPermission(this, permissions)) {
                    CircleDialog.Builder()
                        .setTitle("系统权限设置")
                        .setText("您确定要获取访问相册的权限吗？")
                        .setPositive("确定") { setPermission() }
                        .setNegative("取消", null)
                        .show(supportFragmentManager)
                }
            }.start()
    }

    private fun voice() {
        //弹对话框录音
        startRecord()
        //显示被邀请消息
        CustomAlertDialog.with(this)
            .setCancelable(false)
            .setNegativeButton("取消", View.OnClickListener {
                stopRecord()
            })
            .setPositiveButton(
                "完成",
                View.OnClickListener {
                    stopRecord()
                    uploadAudio()
                    uploadAudioStatus = 1
                    finishVoice()
                })
            .show()

    }


    private fun finishVoice() {
        viewBinding.voiceContent.visibility = View.GONE
        viewBinding.voicePlay.visibility = View.VISIBLE
        viewBinding.voiceDuration.visibility = View.VISIBLE
        viewBinding.delete.visibility = View.VISIBLE
        isVoiceRecord = false

    }

    override fun initData() {
        viewModel.queryDict("task_type").observe(this) {
            if (it == null || it.isEmpty()) {
                return@observe
            }
            orderTypeId = it[0].id
            orderTypeCode = it[0].dictTag
            orderTypeName = it[0].dictName

            viewBinding.dictName.text = it[0].dictName
        }
        viewModel.queryDictByParentId("task_sub_type").observe(this) { list ->
            list.forEach { subType ->
                items.add(
                    SubTypeLabel(
                        subType.id,
                        subType.dictTag,
                        subType.dictName,
                        subType.dictName
                    )
                )
            }
        }
        initAdapter1()
        viewBinding.attachmentRecyclerView.adapter = attachmentAdapter1

        viewModel.uploadSuccess.observe(this) {
            val uploadSuccess: Boolean = it.isSuccess
            val fileName: String = it.fileName
            if (uploadSuccess) {
                picList1.add(it)
            } else {
                displayFailImage1(fileName)
            }
        }
        viewBinding

    }

    override fun uploadTask1(fileName: String?, file: ByteArray?) {
        viewModel.uploadImage(fileName, file)
    }

    private fun submit() {
        val description = viewBinding.description.text.toString().trim()
        val areaName = viewBinding.areaName.text.toString().trim()
        if (orderTypeId.isNullOrEmpty()) {
            ToastUtils.showLong("请选择工单类型")
            return
        }
        if (orderSubTypeId.isNullOrEmpty()) {
            ToastUtils.showLong("请选择子类")
            return
        }
        if (areaName.isNullOrEmpty()) {
            ToastUtils.showLong("请填写地址")
            return
        }
        if (description.isNullOrEmpty()) {
            ToastUtils.showLong("请填写描述")
            return
        }

        if (!uploadImageAttachment1()) {
            return
        }
        setImages()
        val releaseId: String = SPUtils.getInstance().getString(AppConfig.USER_ID)
        val releaseUserName: String = SPUtils.getInstance().getString(AppConfig.USER_NAME)

        viewModel.insertWorkOrder(
            orderTypeId!!, orderTypeCode!!, orderTypeName!!,
            orderSubTypeId!!, orderSubTypeCode!!, orderSubTypeName!!,
            areaName, description, releaseId, releaseUserName,
            "", files.map { it.build() },
            assetId ?: "", assetName ?: ""
        )
            .observe(this) {
                if (it != null) {
                    transform(it.id, it.orderCode)
                }
            }
    }

    private fun transform(orderId: String, orderCode: String) {
        detail.dealType = dealType
        detail.dealWorkOrder = "${orderId},${orderCode}"
//        viewModel.deal(detail).observe(this) {
//            if (it) {
                ToastUtils.showLong("提交成功")
                startActivity(Intent(this, WarningResultActivity::class.java))
                finish()
//            }
//        }
    }

    override fun initView() {
        registerEventBus()
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun handleEvent(event: WarningMessageEvent) {
        detail = event.messageAlarm
    }

    override fun playComplete() {
        isRunning = false
        Glide.with(this).load(R.mipmap.ic_voice_play).into(viewBinding.voicePlay)
    }

    override fun uploadAudio(fileName: String?, file: ByteArray?, duration: Long) {
        this.duration = duration
        viewModel.uploadAudio(fileName, file)
        viewBinding.voiceDuration.post {
            viewBinding.voiceDuration.text = "${duration / 1000}''"
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterEventBus()
    }
}